<?php
/**
 *Static import methods
 */ 
class ImportCue
{
  public static function getReadyFiles()
  {
    $local_files = glob($_SESSION['MczSession']->getHomeDir().'/local_import/*.*');
    return $local_files;
  }
  public static function getUnreadyFiles()
  {
    $local_files = glob($_SESSION['MczSession']->getHomeDir().'/temp/*.*');
    if(!$local_files)
    {
      return array();
    }
    return $local_files;
  }
  
  public static function add($fileName)
  {
    $fileName = trim($fileName);
    if(!empty($fileName))
    {
      $home_dir = $_SESSION['MczSession']->getHomeDir();
      $temp_dir = $home_dir.'/temp';
      if(!is_dir($temp_dir))// create temp dir if needed
      {
        mkdir($temp_dir,0777,TRUE);
      }
      $temp_file = $temp_dir."/".basename($fileName);
      session_write_close();// prevent session lock with big files
      if(Tools::curl_cp($fileName,$temp_file))
      {
        return(Tools::rename_win($temp_file,$home_dir.'/local_import/'.basename($temp_file)));
      }
    }
  }
  
  /**
   *Import procedure
   */     
  public static function import($fileName)
  {
    $fileName = trim($fileName);
    if(empty($fileName))
    {
      return false;
    }
    if(!$_SESSION['MczSession']->can('add_file'))//check user rights
    {
      return false;
    }
    $mimetypes = array('audio/mpeg','audio/x-mp3','audio/x-mpeg','audio/x-wave');
    $home_dir = $_SESSION['MczSession']->getHomeDir();
    $usr_login = $_SESSION['MczSession']->getLogin();
    $temp_dir = $home_dir.'/local_import';
    if(!is_dir($temp_dir))// create temp dir if needed
    {
      mkdir($temp_dir,0777,TRUE);
    }
    
    if(ereg("^(http|https|ftp)?://",$fileName))// copy 1st if filename is a url
    {
      if(!copy($fileName,$temp_dir."/".basename($fileName)))
      {
        return false;
      }
      $fileName = $temp_dir."/".basename($fileName);
      chmod($fileName,0777);
    }
    
    chmod($fileName,0777);
    
    $path_parts = pathinfo($fileName);
    $getID3 = new getID3();
    if(!$fileInfo = $getID3->analyze($fileName))
    {
      return false;
    }
    //print_r($fileInfo);
    //die();
    if(!in_array($fileInfo['mime_type'],$mimetypes))// only allow ogg vorbis and mp3
    {
      return false;
    }
    getid3_lib::CopyTagsToComments($fileInfo);// merge id3v1 and id3v2 tags
    if(empty($fileInfo['comments']['artist'][0]))
    {
      $fileInfo['comments']['artist'][0] = 'unknown';
    }
    if(empty($fileInfo['comments']['album'][0]))
    {
      $fileInfo['comments']['album'][0] = 'unknown';
    }
    if(empty($fileInfo['comments']['title'][0]))
    {
      $fileInfo['comments']['title'][0] = $path_parts['filename'];
    }
    $clean_artist_name = Tools::cleanFileName(noDiacritics($fileInfo['comments']['artist'][0],false));
    $new_path = SND_PATH.$clean_artist_name{0}
                            .'/'
                            .$clean_artist_name
                            .'/'
                            .Tools::cleanFileName(noDiacritics($fileInfo['comments']['album'][0],false))
                            .'/'
                            .Tools::cleanFileName(noDiacritics($fileInfo['comments']['title'][0],false))
                            .'.'.$path_parts['extension'];
    $fileprefix = 1;
    $tmpfilename= $new_path;
    $path_parts = pathinfo($tmpfilename);
    
    if(is_file($new_path))
    {
      if(sha1_file($fileName) == sha1_file($new_path))// if file is the same...
      {
        chmod($fileName,0777);
        unlink($fileName);//delete doubled file
        return false;//... do nothing.
      }
      else
      {
        while(is_file($new_path) and $fileprefix<20)// if file toto.mp3 exists, use toto_1.mp3, and so on...
        {
          $new_path = $path_parts['dirname'].'/'.$path_parts['filename'].'_'.$fileprefix.'.'.$path_parts['extension'];
          $fileprefix++;
        }
      }
    }
    if(!is_dir($path_parts['dirname']))// create new dir if needed
    {
      mkdir($path_parts['dirname'],0777,TRUE);
    }

    if(!Tools::rename_win($fileName,$new_path))
    {
      return false;
    }

    chmod($new_path,0777);

    $sql = "INSERT INTO song values(
      '".uniqid('sng')."',
      '".sqlite_escape_string($usr_login)."',
      '".sqlite_escape_string(strtr($new_path,array(SND_PATH=>'')))."',
      '".sqlite_escape_string($fileInfo['mime_type'])."',
      '".sqlite_escape_string($fileInfo['audio']['bitrate'])."',
      '".sqlite_escape_string($fileInfo['filesize'])."',
      '".sqlite_escape_string($fileInfo['playtime_seconds'])."',
      '".time()."',
      NULL,
      NULL,
      '".sqlite_escape_string(htmlentities(trim($fileInfo['comments']['title'][0]),ENT_QUOTES))."',
      '".sqlite_escape_string(htmlentities(trim($fileInfo['comments']['artist'][0]),ENT_QUOTES))."',
      '".sqlite_escape_string(htmlentities(trim($fileInfo['comments']['album'][0]),ENT_QUOTES))."',
      '".sqlite_escape_string(htmlentities(trim($fileInfo['comments']['genre'][0]),ENT_QUOTES))."',
      '".sqlite_escape_string(htmlentities(Song::getBestTag('comment',$fileInfo),ENT_QUOTES))."',
      '".sqlite_escape_string($fileInfo['comments']['year'][0])."',
      '".sqlite_escape_string(Song::getBestTag('track',$fileInfo))."',
      NULL,
      NULL
    );";

    $dbh = new dbSql();
    $res = $dbh->exec($sql);
    return($res);
  }
}
?>
